package com.example.broadcasttest1;

import androidx.appcompat.app.AppCompatActivity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends AppCompatActivity {
    private NetworkChangeReceiver networkChangeReceiver;

        //IntentFilter intentFilter;
        @Override
        protected void onCreate(Bundle savedInstanceState){
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            IntentFilter intentFilter=new IntentFilter();
            intentFilter.addAction("android.net.conn.CONNECTIVITY_CHANGE");
            networkChangeReceiver=new NetworkChangeReceiver();
            registerReceiver(networkChangeReceiver,intentFilter);
        }
        @Override
        protected void onDestroy(){
            super.onDestroy();
            unregisterReceiver(networkChangeReceiver);
        }
        public class NetworkChangeReceiver extends BroadcastReceiver{
            private static final String TAG ="NetworkChangeReceiver";
            @Override
            public void onReceive(Context context, Intent intent){
                ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                boolean isConnected = activeNetwork != null &&
                        activeNetwork.isConnectedOrConnecting();
                boolean isWiFi = activeNetwork.getType() == ConnectivityManager.TYPE_WIFI;
                if (isConnected==true){
                    if (isWiFi==true){
                        Log.d(TAG,"当前网络类型为WiFi");
                    }else{
                        Log.d(TAG,"当前网络类型为移动网络");
                    }
                }else{
                    Log.d(TAG,"当前网络已断开");
                }

            }
        }
}